package org.come.bean;

import org.come.test.Main;
import org.come.until.GsonUtil;
import org.come.until.Util;

import java.util.ArrayList;
import java.util.List;

public class LoginInfo {
    private List<LoginRoleInfo> loginRoleInfos;

    public LoginInfo() {

    }

    public void updateLoginRole(LoginRoleInfo roleInfo) {
        if (loginRoleInfos == null) {
            loginRoleInfos = new ArrayList<>();
        }
        boolean isAdd = true;
        for (int i = 0; i < loginRoleInfos.size(); i++) {
            if (loginRoleInfos.get(i).contrast(Main.frame.getRoleInfo())) {
                loginRoleInfos.set(i, roleInfo);
                isAdd = false;
                break;
            }
        }
        if (isAdd) {
            loginRoleInfos.add(0, Main.frame.getRoleInfo());
        }

        // 顶掉多余的角色
        for (int i = loginRoleInfos.size() - 1; i > 4; i--) {
            loginRoleInfos.remove(i);
        }

        // 写入信息
        Util.writeUserInfo(GsonUtil.getGsonUtil().getgson().toJson(this));
    }

    public void delCommonlyUsedRoles(LoginRoleInfo loginRoleInfo) {//移除角色
        for (int i = loginRoleInfos.size() - 1; i >= 0; i--) {
            LoginRoleInfo roleInfo = loginRoleInfos.get(i);
            if (roleInfo.getAccount().equals(loginRoleInfo.getAccount())
                    && roleInfo.getPassword().equals(loginRoleInfo.getPassword())
                    && roleInfo.getRoleId().compareTo(loginRoleInfo.getRoleId()) == 0) {
                loginRoleInfos.remove(i);
            }
        }
        Util.writeUserInfo(GsonUtil.getGsonUtil().getgson().toJson(this));
    }

    public List<LoginRoleInfo> getLoginRoleInfos() {
        return loginRoleInfos;
    }

    public void setLoginRoleInfos(List<LoginRoleInfo> loginRoleInfos) {
        this.loginRoleInfos = loginRoleInfos;
    }
}
